package org.xzx.shop_api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xzx.shop_api.entity.Members;
import org.xzx.shop_api.entity.IdCard;
import org.xzx.shop_api.service.MembersService;
import org.xzx.shop_api.service.QiniuService;
import org.xzx.shop_api.service.idCardService;
import org.xzx.shop_api.utils.ImageUtils;
import org.xzx.shop_api.utils.JsonResult;
import org.xzx.shop_api.utils.Md5Utils;
import org.xzx.shop_api.utils.Tool;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/members")
public class MembersController {
    @Autowired
    private MembersService membersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Members members;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private idCardService idCardService;
    @Autowired
    private IdCard idCard;
    @PostMapping("register")
    public JsonResult register(@RequestParam("mobile") String mobile,
                               @RequestParam("code") String code) {
        //重复性验证
        Members membersInfo = membersService.getMembersByUsername(mobile);
        if (membersInfo != null) {
            return JsonResult.failed("改手机号已经注册，请更换手机号");
        }
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null||!smsCode.equals(code)) {
            return JsonResult.failed("验证码错误");
        }
        members.setMobile(mobile);
        members.setUsername(mobile);
        members.setRegisteredTime(Tool.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        System.out.println(members);
        int result = membersService.insertMember(members);
        if (result == 0){
            return JsonResult.failed("注册失败");
        }
        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        return JsonResult.success("注册成功",null);
    }
    //获取短信验证码
    /**
     * body  x-www-from
     */
    @PostMapping("get_sms_code")
    public JsonResult getSmsCode(@RequestParam("mobile") String mobile) {
        //验证手机号格式
        if (mobile  == null || mobile.trim().isEmpty() | !Tool.isMobile(mobile)) {
            return JsonResult.failed("请输入正确的手机号");
        }
        //生成验证码
        long randomNum = Tool.generateRandomNumber(4);
        //String message = "【上海星知心教育科技】您的验证码是"+randomNum+",1分钟内有效。若非本人操作请忽略此消息";
        //调用短信接口
        //SMSUtils.sendSms(mobile, message);
        //存储到redis
        stringRedisTemplate.opsForValue().set(mobile, String.valueOf(randomNum),60*60, TimeUnit.SECONDS);
        return JsonResult.success("获取成功",randomNum);
    }

    //登录
    @PostMapping("login")
    public JsonResult login(@RequestParam("mobile") String mobile,
                            @RequestParam("code") String code){
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null||!smsCode.equals(code)) {
            return JsonResult.failed("验证码不正确");
        }
        Members membersInfo = membersService.getMembersByUsername(mobile);
        if (membersInfo == null) {
            return JsonResult.failed("登录失败");
        }

        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        HashMap<Object, Object> mapMembersInfo = new HashMap<>();
        mapMembersInfo.put("id", membersInfo.getId());
        mapMembersInfo.put("username", membersInfo.getUsername());
        mapMembersInfo.put("mobile", membersInfo.getMobile());
        return JsonResult.success("登录成功",null);
    }

    //修改密码
    @PostMapping("update_password")
    public JsonResult updatePassword(@RequestParam("mobile")String mobile,
                                     @RequestParam("code")String code,
                                     @RequestParam("password")String password,
                                     @RequestParam("confirm_password")String confirm_password) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null||!smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误");
        }
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)){
            return JsonResult.failed("密码格式不正确");
        }
        //验证密码一致
        if (!password.equals(confirm_password)){
            return JsonResult.failed("两次密码输入不一致");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updateMember(mobile, safePassword);
        if (result == 0){
            return JsonResult.success("设置成功",null);
        }
        //删除缓存验证码
        //stringRedisTemplate.delete(mobile);
        return JsonResult.success("设置成功",null);
    }

    //修改支付密码
    @PostMapping("update_pay_password")
    public JsonResult updatePayPassword(@RequestParam("id") int id,
                                        @RequestParam("password") String password,
                                        @RequestParam("confirm_password") String confirmPassword) {
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)){
            return JsonResult.failed("密码格式不正确");
        }
        if (!password.equals(confirmPassword)){
            return JsonResult.failed("两次密码输入不一致，请重新输入");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updatePayPassword(id, safePassword);
        if(result == 0){
            return JsonResult.failed("设置成功");
        }
        return JsonResult.success("设置成功",null);
    }
    //修改手机号
    @PostMapping("update_mobile")
    public JsonResult updateMobile (@RequestParam("id") int id,
                                    @RequestParam("mobile") String mobile,
                                    @RequestParam("code")String code) {
        //验证手机号码格式
        if (mobile == null || mobile.trim().isEmpty()||!Tool.isMobile(mobile)) {
            return JsonResult.failed("手机号格式不正确");
        }

        //短信验证密码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null|| !smsCode.equals(code)) {
            return JsonResult.failed("验证码错误");
        }
        //验证手机号码重复
        Members membersInfo = membersService.getMembersByMobile(mobile);
        if (membersInfo != null && id != membersInfo.getId()) {
            return JsonResult.failed("手机号码已经占用，请更换");
        }
        int result = membersService.updateMobile(id, mobile);
        if (result == 0){
            return JsonResult.failed("设置失败");
        }
        return JsonResult.success("设置成功",null);
    }

    //我的信息接口
    @GetMapping("my")
    public JsonResult my(@RequestParam("id") int id) {
        Members membersInfo = membersService.getMembersById(id);
        HashMap<Object, Object> mapMembersInfo = new HashMap<>();
        mapMembersInfo.put("id", membersInfo.getId());
        mapMembersInfo.put("username", membersInfo.getUsername());
        mapMembersInfo.put("mobile", membersInfo.getMobile());
        String genderDesc = "保密";
        if (membersInfo.getId() == 1){
            genderDesc = "帅哥";
        }else if (membersInfo.getId() == 0){
            genderDesc = "美女";
        }
        mapMembersInfo.put("gender", genderDesc);
        mapMembersInfo.put("nickname", membersInfo.getNickname());
        mapMembersInfo.put("birthday", membersInfo.getBirthday());
        mapMembersInfo.put("logo", membersInfo.getLogo());
        mapMembersInfo.put("isAuth", membersInfo.getIsAuth());

        return JsonResult.success("获取成功",mapMembersInfo);
    }

    //修改个人信息接口
    @PostMapping("update_myInfo")
    public JsonResult updateMyInfo(@RequestParam("id") int id,
                                   @RequestParam("username")String username,
                                   @RequestParam("nickname")String nickname,
                                   @RequestParam("birthday")String birthday,
                                   @RequestParam(value = "gender",defaultValue = "2")String gender){
        //用户名重复性验证
        Members membersInfo = membersService.getMembersByUsername(username);
        if (membersInfo != null && id != membersInfo.getId()) {
            return JsonResult.failed("该用户名已经使用，请更换");
        }
        int result = membersService.updateMyInfo(id, username, nickname, Integer.parseInt(gender), birthday);
        if (result == 0){
            return JsonResult.failed("更新失败");
        }
        return JsonResult.success("更新成功",null);
    }

    @PostMapping("upload_logo")
    public JsonResult uploadLogo(@RequestParam("id") int id,
                                 @RequestParam("logo") MultipartFile logo) throws IOException {
        //限制文件必选
        if (logo == null || logo.isEmpty()) {
            return JsonResult.failed("请选择上传的图片");
        }
        //验证图片格式
        //获取扩展名
        String extName = ImageUtils.getExtName(logo.getContentType());
        if (!ImageUtils.isAllowedExtName(extName)) {
            return JsonResult.failed("请上传png,jpeg,jpg格式图片");
        }
        //验证图片大小
        if (!ImageUtils.isAllowedImageSize(logo.getSize())) {
            return JsonResult.failed("图片大小不能超过2M");
        }
        //重新命名文件
        String newLogoName = "logo_"+Tool.getCurrentTime()+"." + extName;

        //logo.transferTo(new File("D:/images", newLogoName));
        //上传到七牛云存储
        try {
            String qiniuLogoUrl = qiniuService.uploadFile(logo);
            //更新头像
            int upResult = membersService.updateLogo(id, qiniuLogoUrl);
            if (upResult == 0) {
                JsonResult.failed("更新失败");
            }
            return JsonResult.success("更新成功",qiniuLogoUrl);
        } catch (Exception e) {
            return JsonResult.failed(e.getMessage());
        }
        //return JsonResult.success("ok",null);
    }

    //身份证实名认证上传
    @PostMapping("id_card_upload")
    public JsonResult idCardUpload(@RequestParam("id") int id,
                           @RequestParam("real_name") String realName,
                           @RequestParam("idcard_number") String idCardNumber,
                                 @RequestParam("card_image") MultipartFile[] cardImage) throws IOException {
        //限制文件必选
        if (cardImage == null || cardImage.length == 0) {
            return JsonResult.failed("请选择上传的图片");
        }
        HashMap<Object, Object> mapCardImageInfo = new HashMap<>();
        int i = 1;
        //多图接收
        for (MultipartFile image:cardImage) {
            //验证图片格式
            //获取扩展名
            String extName = ImageUtils.getExtName(image.getContentType());
            if (!ImageUtils.isAllowedExtName(extName)) {
                return JsonResult.failed("请上传png,jpeg,jpg格式图片");
            }
            //验证图片大小
            if (!ImageUtils.isAllowedImageSize(image.getSize())) {
                return JsonResult.failed("图片大小不能超过2M");
            }
            //上传到七牛云存储
            try {
                String qiniuLogoUrl = qiniuService.uploadFile(image);
               /* //更新头像
                int upResult = membersService.updateLogo(id, qiniuLogoUrl);
                if (upResult == 0) {
                    JsonResult.failed("认证失败");
                }*/
                mapCardImageInfo.put("card_image"+i,qiniuLogoUrl);

            } catch (Exception e) {
                return JsonResult.failed(e.getMessage());
            }
            i++;
        }
        return JsonResult.success("ok", mapCardImageInfo);
    }


    //身份证实名认证提交
    @PostMapping("auth")
    public JsonResult auth(@RequestParam("id") int id,
                                   @RequestParam("real_name") String realName,
                                   @RequestParam("idcard_number") String idCardNumber,
                                   @RequestParam("id_card_image_front") String idCardImageFront,
                           @RequestParam("id_card_image_back") String idCardImageBack) throws IOException {

        //验证姓名不为空
        if (realName.isEmpty()){
            return JsonResult.failed("请输入真实姓名");
        }
        //验证身份证号码
        if (!Tool.isValidIdCard(idCardNumber)){
            return JsonResult.failed("身份证号码格式错误");
        }
        idCard.setId(id);
        idCard.setRealName(realName);
        idCard.setIdCardNumber(idCardNumber);
        idCard.setIdCardImageFront(idCardImageFront);
        idCard.setIdCardImageBack(idCardImageBack);
        int result = idCardService.insertIdCard(idCard);
        if (result == 0){
            return JsonResult.failed("认证失败");
        }
        //更新会员标识
        membersService.updateIsAuth(id,1);
        return JsonResult.success("认证成功", null);
    }
}

















